<!--
 * @Author: MarioGo
 * @Date: 2021-11-10 10:16:38
 * @LastEditTime: 2021-11-11 13:52:54
 * @LastEditors: MarioGo
 * @Description: 文件描述
 * @FilePath: /zheye/src/components/ValidateForm.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->
<template>
  <form class="validate-form-container">
    <!-- 插槽表单区域 -->
    <slot name="default"></slot>
    <!-- 插槽按钮区域 -->
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <div type="submit" class="btn btn-danger">登录</div>
      </slot>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue';
import mitt from 'mitt';
export const emitter = mitt();
type validateFunArr = () => boolean;
type clearFunArr = () => void;
export default defineComponent({
  name: 'ValidateForm',
  emits: ['form-submit'],
  setup(props, context) {
    let funcArr: validateFunArr[] = [];
    let clear_funcArr: clearFunArr[] = [];
    const submitForm = () => {
      //循环调用funcArr中的方法
      const validateResult = funcArr.map((func) => func()).every((result) => result);
      context.emit('form-submit', validateResult);
    };
    const clear_submitForm = (): void => {
      //循环调用funcArr中的方法
      clear_funcArr.map((func) => func());
    };
    const callback = (func: any) => {
      funcArr.push(func);
    };
    const clear_callback = (func: any) => {
      clear_funcArr.push(func);
    };
    emitter.on('form-item-created', callback);
    emitter.on('form-item-clear', clear_callback);
    onUnmounted(() => {
      emitter.off('form-item-created', callback);
      emitter.on('form-item-clear', clear_callback);
      funcArr = [];
      clear_funcArr = [];
    });
    return {
      submitForm,
      clear_submitForm,
    };
  },
});
</script>

<style scoped></style>
